<?php


namespace app\index\controller;

use app\admin\service\RbacService;
use app\common\controller\CommonController;
use app\common\exception\ParameterFailedException;
use app\common\exception\NotFoundException;
use app\common\model\AddressModel;
use app\common\service\Lang;
use app\common\validate\AddressValidate;
use think\facade\Db;
use think\Request;

class AddressController extends CommonController
{
    public function getAddress(Request $request)
    {
        $params      = self::getParam(['address_id']);
        (new AddressValidate())->goCheck(__FUNCTION__, $params);
        $model = (new AddressModel())->getAddress([
            [
                'user_id',
                '=',
                $request->userModel->getData('id'),
            ],
            [
                'id',
                '=',
                $params['address_id'],
            ],
        ]);
        if (!$model) {
            throw new NotFoundException();
        }
        $res = $model->toArray();
        return retJson(Lang::GETDone, $res);
    }

    public function getAddressList(Request $request)
    {

        $models      = (new AddressModel())->getAddressList([
            [
                'user_id',
                '=',
                $request->userModel->getData('id'),
            ],
        ]);
        if ($models->isEmpty()) {
            $res = [];
        }
        else {
            $res = $models->toArray();
        }
        return retJson(Lang::GETDone, $res);
    }

    public function postAddress(Request $request)
    {
        $params      = self::getParam([
            'name',
            'mobile_number',
            'province',
            'city',
            'area',
            'detail',
            'is_default',
        ]);
        (new AddressValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $oldModel = (new AddressModel())->where('name', $params['name'])
                ->where('mobile_number', $params['mobile_number'])
                ->where('province', $params['province'])
                ->where('city', $params['city'])
                ->where('area', $params['area'])
                ->where('detail', $params['detail'])
                ->where('user_id', $request->userModel->getData('id'))
                ->find();
            if ($oldModel) {
                throw new ParameterFailedException(['msg' => '已存在该数据']);
            }

            $model                = new AddressModel();
            $model->name          = $params['name'];
            $model->mobile_number = $params['mobile_number'];
            $model->province      = $params['province'];
            $model->city          = $params['city'];
            $model->area          = $params['area'];
            $model->detail        = $params['detail'];
            $model->is_default    = $params['is_default'];
            $model->user_id       = $request->userModel->getData('id');
            if ($params['is_default'] === true) {
                (new AddressModel())->where('user_id', $request->userModel->getData('id'))->save(['is_default' => false]);
            }

            $model->save();

            Db::commit();
            return retJson(Lang::POSTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function putAddress(Request $request)
    {

        $params      = self::getParam([
            'address_id',
            'name',
            'mobile_number',
            'province',
            'city',
            'area',
            'detail',
            'is_default',
        ]);
        (new AddressValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $model = AddressModel::where('id', $params['address_id'])
                ->where('user_id', $request->userModel->getData('id'))
                ->find();
            if (!$model) {
                throw new NotFoundException();
            }

            $model->name          = $params['name'];
            $model->mobile_number = $params['mobile_number'];
            $model->province      = $params['province'];
            $model->city          = $params['city'];
            $model->area          = $params['area'];
            $model->detail        = $params['detail'];
            $model->is_default    = $params['is_default'];
            if ($params['is_default'] === true) {
                (new AddressModel())->where('user_id', $request->userModel->getData('id'))->save(['is_default' => false]);
            }
            $model->save();

            Db::commit();
            return retJson(Lang::PUTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function deleteAddress(Request $request)
    {

        $params      = self::getParam(['address_id']);
        (new AddressValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $model = AddressModel::where('id', $params['address_id'])
                ->where('user_id', $request->userModel->getData('id'))
                ->find();
            if (!$model) {
                throw new NotFoundException();
            }

            $model->delete_time = NOW_TIME;
            $model->save();

            Db::commit();

            return retJson(Lang::DELETEDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }
}